package com.xing.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import lombok.Getter;
import lombok.Setter;

import org.apache.struts2.json.annotations.JSON;
import org.springframework.stereotype.Controller;

import com.xing.model.SubsidiaryInfo;
import com.xing.service.SubsidiaryService;
import com.xing.util.QueryBuilder;

@Controller
public class SubsidiaryAction extends BaseAction {
	/** */
	/**
     * 
     */
	private static final long serialVersionUID = 1L;

	@Resource
	private SubsidiaryService subsidiaryService;

	public String list() throws Exception {

		System.out.println("do list method!");
		
//		List<SubsidiaryInfo> list = subsidiaryService.getList();
//		
//		getRequest().put("subsidiaryList", list);
		
		return "list";
		
	}
	
	@Override
	public String dataGrid() {
		
		Map<String, Object> map = subsidiaryService.getListAndCount(buildQueryCondition(), getPage(), getRows());
		setDataGrid(map);
		
		return "dataGrid";
	} 
	
	public String addSubsidiary() throws Exception {
		
		System.out.println("do addSubsidiary method!");
		
		SubsidiaryInfo info =  createSubsidiaryInfo();
		subsidiaryService.addSubsidiary(info);
		
		setMessage("msg", "新增成功.");
		
		return list();
	}
	
	public String modifySubsidiary() throws Exception {
		
		SubsidiaryInfo info =  createSubsidiaryInfo();
		subsidiaryService.updateSubsidiary(info);
		
		setMessage("msg", "修改成功.");
		
		return list();
	}
	
	@JSON(serialize=false)
	public String getSubsidiary() throws Exception {
		
		System.out.println("do getSubsidiary method!");
		
		jsonInfo = subsidiaryService.getSubsidiary(subsidiaryId);
		
		return "getObject";
	}
	
	public String deleteSubsidiary() throws Exception {
		
		System.out.println("do deleteSubsidiary method!");
		
		subsidiaryService.deleteSubsidiary(getDeleteId());
		
		setMessage("msg", "删除成功.");
		
		return list();
	}

	private SubsidiaryInfo createSubsidiaryInfo() {
		
		SubsidiaryInfo info = new SubsidiaryInfo();
		info.setName(name);
		info.setAddress(address);
		info.setPhone(phone);
		info.setRemark(remark);
		if (subsidiaryId > 0) {
			info.setSubsidiaryId(subsidiaryId);
		}
		return info;
	}
	
	private List<String> buildQueryCondition() {
		List<String> conditionList = new ArrayList<String>();
		
		QueryBuilder.buildQueryCondition(query_subsidiaryName, "c.name", QueryBuilder.LIKE, conditionList);
		
		return conditionList;
	}
	
	private SubsidiaryInfo jsonInfo;
	@JSON(name="subsidiaryInfo")
	public SubsidiaryInfo getJsonInfo() {
		return jsonInfo;
	}
	
	@Getter @Setter private String query_subsidiaryName;

	@Getter @Setter private int subsidiaryId;
	@Getter @Setter private String name;
	@Getter @Setter private String address;
	@Getter @Setter private String phone;
	@Getter @Setter private String remark;

}
